//
//  BinarySortControl.swift
//  AlgorithmDEMO
//
//  Created by meitianhui2 on 2018/1/13.
//  Copyright © 2018年 DeLongYang. All rights reserved.
/*
    这里 使用 二分法 来求  X^X = 2 的近似值 也就是 2 的平方根 把 精度放在 0.005 之间
 */

import UIKit

class BinarySortControl: BaseControl {
    
    override func executeAlgorithm() {
        
        var x1:Double = 1
        var x2:Double = 2
        
        while (getAbsoluteValueForTwo(num1: x2, num2: x1) > 0.005) {
            
            let m:Double = (x1+x2)/2.0000000000
            
            if squareFunction(num: m) == 0 {
                print("solution is \(m)")
            }else{
                let amass:Double = binaryFunction(num1: x1, num2: m)
                if amass > 0{
                    x1 = m
                }else{
                    x2 = m
                }
            }
            
        }
        
        print("x1: is\(x1)  x2: is\(x2)")
    }
    
    // 找两个数 之间的绝对值
    func getAbsoluteValueForTwo(num1:Double,num2:Double) -> Double {
        if num1>num2 {
            return num1 - num2
        }else{
            return num2 - num1
        }
    }
    
    //  平方函数
    func squareFunction(num:Double) -> Double {
        return pow(num, 2) - 2
    }
    
    // 自定义的 x的平方 - 2 函数
    func binaryFunction(num1:Double,num2:Double) -> Double {
        return squareFunction(num: num1)*squareFunction(num: num2)
    }

}
